# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class EquipmentAcceptance(Document):
    def autoname(self):
        """自动生成验收单号"""
        from frappe.utils import now_datetime
        now = now_datetime()
        year = now.year
        
        # 获取当年的序号
        count = frappe.db.count("Equipment Acceptance", 
                               filters={"creation": [">=", f"{year}-01-01"]}) + 1
        
        self.acceptance_id = f"ACC-{year}-{count:05d}"
        self.name = self.acceptance_id

    def validate(self):
        """验证数据"""
        # 从采购收据获取信息
        if self.purchase_receipt:
            pr = frappe.get_doc("Purchase Receipt", self.purchase_receipt)
            self.equipment_name = pr.items[0].item_name if pr.items else ""
            self.supplier = pr.supplier
            self.delivery_date = pr.posting_date
        
        if not self.acceptance_date:
            self.acceptance_date = frappe.utils.today()

    def on_submit(self):
        """提交验收表"""
        if self.overall_result == "合格":
            self.create_equipment_record()
        
        self.update_purchase_request_status()

    def create_equipment_record(self):
        """验收合格后创建设备档案"""
        try:
            # 获取采购收据信息
            pr = frappe.get_doc("Purchase Receipt", self.purchase_receipt)
            item = pr.items[0] if pr.items else None
            
            if not item:
                frappe.throw("采购收据中没有找到物料信息")
            
            # 创建设备档案
            equipment = frappe.get_doc({
                "doctype": "Equipment",
                "equipment_name": self.equipment_name,
                "equipment_category": self.get_equipment_category(),
                "supplier": self.supplier,
                "purchase_date": self.delivery_date,
                "purchase_cost": item.amount,
                "status": "使用中",
                "condition": "优秀"
            })
            equipment.insert()
            
            # 创建设备履历
            equipment.create_equipment_history("验收确认", f"设备验收合格，验收单号：{self.acceptance_id}")
            
            frappe.msgprint(f"已创建设备档案：{equipment.equipment_code}")
            
        except Exception as e:
            frappe.log_error(f"创建设备档案失败: {str(e)}", "Equipment Acceptance")
            frappe.throw(f"创建设备档案失败: {str(e)}")

    def get_equipment_category(self):
        """获取设备分类"""
        # 尝试从设备名称推断分类
        categories = frappe.get_all("Equipment Category", fields=["name", "category_name"])
        
        for cat in categories:
            if cat.category_name in self.equipment_name:
                return cat.name
        
        # 默认返回第一个分类
        return categories[0].name if categories else None

    def update_purchase_request_status(self):
        """更新采购申请状态"""
        # 查找相关的采购申请
        pr_items = frappe.get_all("Purchase Request Item",
                                 filters={"purchase_receipt": self.purchase_receipt},
                                 fields=["parent"])
        
        if pr_items:
            # 查找EAM采购申请
            eam_requests = frappe.get_all("Equipment Purchase Request",
                                        filters={"purchase_receipt": self.purchase_receipt})
            
            for req in eam_requests:
                eam_req = frappe.get_doc("Equipment Purchase Request", req.name)
                eam_req.workflow_state = "已验收"
                eam_req.save()

    def calculate_overall_result(self):
        """计算总体验收结果"""
        results = [
            self.equipment_dept_result,
            self.production_dept_result,
            self.quality_dept_result,
            self.purchase_dept_result
        ]
        
        # 如果有任何一个部门验收不合格，则总体不合格
        if "不合格" in results:
            self.overall_result = "不合格"
        elif "有条件合格" in results:
            self.overall_result = "有条件合格"
        elif all(r == "合格" for r in results if r):
            self.overall_result = "合格"
        else:
            self.overall_result = ""